//
//  AddGameDetailViewController.swift
//  FootballDataRecord
//
//  Created by Xx Jiang on 2020/1/7.
//  Copyright © 2020 Xx Jiang. All rights reserved.
//

import UIKit
import SnapKit
class AddGameDetailViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
    @IBOutlet weak var tableview: UITableView!
    enum TeamType:Int {
        case leftTeam = 0
        case rightTeam = 1
    }
    var leftTeam:[PlayerModel]?
    var rightTeam:[PlayerModel]?
    
    let sectionTitleArr = ["进球","射门","射正","越位","角球","犯规","黄牌","红牌"]   //section的title 和  数据的类型
    
    
    func getPlayerArrWithTeamModel(model:TeamModel)->([[PlayerModel]]){
        var shoufaArr = [PlayerModel]()
        var tibuArr = [PlayerModel]()
        let teamArr:[PlayerModel] = TeamModel.getTeamPlayerListWihtTeamID(teamID: model.teamID!)
        if teamArr.count > 0  {
            for playModel in teamArr {
                if playModel.playerType == "0" {
                    shoufaArr.append(playModel)
                }else{
                    tibuArr.append(playModel)
                }
            }
        }
        return [shoufaArr,tibuArr]
    }
    
    var teamA:TeamModel?{
        didSet{
            leftTeam = TeamModel.getTeamPlayerListWihtTeamID(teamID: self.teamA!.teamID!)
            
            leftTeamName.text = teamA?.teamName
            leftIcon.image = getImage(path: DYStringIsEmpty(value: teamA!.teamHead as AnyObject?) ? "":teamA!.teamHead!)
            rightTeamName.text = teamB?.teamName
        }
    }
    var teamB:TeamModel? {
        didSet{
            rightTeam = TeamModel.getTeamPlayerListWihtTeamID(teamID: self.teamB!.teamID!)
            rightTeamName.text = teamB?.teamName
            rightIcon.image = getImage(path: DYStringIsEmpty(value: teamB!.teamHead as AnyObject?) ? "":teamB!.teamHead!)
        }
    }
    
    @IBOutlet weak var scoreLabel: UILabel!
    @IBOutlet weak var leftIcon: UIImageView!
    @IBOutlet weak var rightTeamName: UILabel!
    @IBOutlet weak var leftTeamName: UILabel!
    @IBOutlet weak var rightIcon: UIImageView!
    var matchModel:MatchModel?{
        didSet{
            if !DYStringIsEmpty(value: self.matchModel?.matchId as AnyObject?){
                MatchDataModel.getMatchDataModelWithID(matchDataID: "\(self.matchModel?.matchId ?? "")_team_\(self.matchModel?.matchTeamA ?? "")") { (rs) in
                    if rs is MatchDataModel{
                        self.matchDataModelA = (rs as! MatchDataModel)
                    }
                }
                
                MatchDataModel.getMatchDataModelWithID(matchDataID: "\(self.matchModel?.matchId ?? "")_team_\(self.matchModel?.matchTeamA ?? "")") { (rs) in
                    if rs is MatchDataModel{
                        self.matchDataModelB = (rs as! MatchDataModel)
                    }
                }
            }
            
            if !DYStringIsEmpty(value: self.matchModel?.matchScoreA as AnyObject?) && !DYStringIsEmpty(value: self.matchModel?.matchScoreB as AnyObject?) {
            scoreLabel.text = "\(matchModel?.matchScoreA ?? "0")  -  \(matchModel?.matchScoreB ?? "0")"
            }
        }
    }
    var matchDataModelA:MatchDataModel?
    var matchDataModelB:MatchDataModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setTableview()
        //哪个队点击的哪种类型的stepper
        //左边的队
        weak var __weakself = self
        NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "leftTeamAlertPickerView"), object: nil, queue: .main) { (notification) in
            let cellType = notification.userInfo!["post"] as! String
            let index = notification.userInfo!["indexInTableview"] as! Int
            __weakself?.showPickerView(mode: .componentSingle, title: cellType, datasource: __weakself!.leftTeam! , type: cellType , team: .leftTeam,index: index)
        }
        //右边的队伍
        NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "rightTeamAlertPickerView"), object: nil, queue: .main) { (notification) in
            let cellType = notification.userInfo!["post"] as! String
            let index = notification.userInfo!["indexInTableview"] as! Int
            __weakself?.showPickerView(mode: .componentSingle, title: cellType, datasource: __weakself!.rightTeam!, type: cellType , team: .rightTeam,index: index)
        }
        
    }
    
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    func setTableview()  {
        self.tableview.delegate = self
        self.tableview.dataSource = self
//        self.tableview.register(UINib.init(nibName: "JGJAddDataCell", bundle: nil), forCellReuseIdentifier: "JGJAddDataCell")
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionTitleArr.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = Bundle.main.loadNibNamed("JGJAddDataCell", owner: nil, options: nil)?.last as! JGJAddDataCell
        cell.indexInTableview = indexPath.section  //相当于在数组中的位置 不是 row的位置
        cell.cellType = sectionTitleArr[indexPath.section]
        cell.matchModel = matchModel
        if matchDataModelA != nil {
            cell.matchDataModelA = matchDataModelA
        }
        if matchDataModelB != nil {
            cell.matchDataModelB = matchDataModelB
        }
        return cell
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionTitleArr[section]
    }
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        let headerView = view as! UITableViewHeaderFooterView
        headerView.textLabel?.textColor = .white
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.0000001
    }
    
    //左边换人
    @IBAction func teamAChangePlayer(_ sender: Any) {
        showPickerView(mode: .componentMulti, title: "换下---->换上", datasource: getPlayerArrWithTeamModel(model: teamA!) as [AnyObject], type: "换人",team:.leftTeam)
    }
    //右边换人
    @IBAction func teamBChangePlayer(_ sender: Any) {
        showPickerView(mode: .componentMulti, title: "换下---->换上", datasource: getPlayerArrWithTeamModel(model: teamB!) as [AnyObject], type: "换人",team: .rightTeam)
    }
    
    func changeMatchdata(value:String,model:AnyObject,dataKey:String){
        var matchDataID:String?
        if  model is TeamModel {
            let teamModel = model as! TeamModel
            if DYStringIsEmpty(value: teamModel.teamID as AnyObject) {
                return
            }
            matchDataID = "\(matchModel?.matchId ?? "")_team_\(teamModel.teamID ?? "")"
        }else{
            let player = model as! PlayerModel
            if DYStringIsEmpty(value: player.playerID as AnyObject?){
                return
            }
            matchDataID = "\(matchModel?.matchId ?? "")_player_\(player.playerID ?? "")"
        }
        
        MatchDataModel.getMatchDataModelWithID(matchDataID:matchDataID!) { (rs) in
            if rs is MatchDataModel{
                DispatchQueue.main.async {
                    let model = rs as! MatchDataModel
                    model.setValue(value, forKey: matchDataKeyDic[dataKey]!)
                    DHDataBaseOperate.changeValuesWithModel(model: model, keys: ["mainKey":DHMatchDataID,"valueKey":matchDataKeyDic[dataKey] as Any]) { (rs) in
                        if rs.isEqual(1)
                        {
                            print("插入成功")
                        }
                    }
                }
            }else{
                print("查询失败")
            }
        }
    }
    
    //显示选择框框   参数： 单列/多列  标题  数据源  点击的哪个类型的cell  cell所在的第几行
    func showPickerView(mode:BRStringPickerMode,title:String,datasource:[AnyObject],type:String,team:TeamType,index:Int? = nil) {
        print("\(team)的队伍")
        let pickerview = BRStringPickerView.init()
        pickerview.pickerMode = mode
        pickerview.title = title
        pickerview.dataSourceArr = datasource
        pickerview.selectIndexs = [0,0]
        pickerview.isAutoSelect = false
        
        //单列的选择结果
        pickerview.resultModelBlock = { (resultModel) in
            if resultModel?.value != nil {
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeCount"), object: resultModel?.value, userInfo: ["team":team,"indexInTableview":index as Any])
            }
        }
        
        //多列的选择结果
        pickerview.resultModelArrayBlock = { (resultmodel) in
            print("换下---》\(resultmodel![0].value!)")
            let playerA = resultmodel![0].value as! PlayerModel
            let playerB = resultmodel![1].value as! PlayerModel
            let dateModel = DateModel()
            dateModel.now()
            let timeString = "\(dateModel.year)-\(dateModel.month)-\(dateModel.day) \(dateModel.hour):\(dateModel.minute):\(dateModel.second)"
            self.changeMatchdata(value: timeString, model: playerA, dataKey: "换人")
            self.changeMatchdata(value: timeString, model: playerB, dataKey: "换人")
            //数据库操作 。。。获取时间 换上时间   换下时间。。。
        }
        
        pickerview.cancelBlock = {
            print("点击了取消")
            //            if type != "换人" {
            //                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "clickCancle"), object: nil, userInfo: ["team":team,"indexInTableview":index as Any])
            //            }
        }
        pickerview.show()
    }
    
    
    
}
